package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.Result.Requests;
import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.entity.PaAgent;
import cn.chinaflame.pagodas.entity.PaMember;
import cn.chinaflame.pagodas.entity.YwSession;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.handle.HandlerException;
import cn.chinaflame.pagodas.repository.YwSessionRepository;
import cn.chinaflame.pagodas.utils.Jackson;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * session服务
 *
 * @author created by boming
 * @date 2018年1月15日 下午1:57:51
 */
@Service

public class SessionService {

    private Logger log = LoggerFactory.getLogger(SessionService.class);
    @Autowired
    private YwSessionRepository ywSessionRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 保存session
     *
     * @param sessionId
     * @param userid
     * @param userProjectType
     * @param object
     * @return
     */
    public String generateSession(String sessionId, String userid, String userProjectType, Object object) {
        log.info("生成session信息sessionid:{},userid:{},userProjectType:{},object:{}", sessionId, userid, userProjectType, object);
        YwSession session = new YwSession();
        String sessionId1 = String.valueOf(System.currentTimeMillis());
        session.setId(sessionId1);
        session.setPeriod(Sysconst.SESSION_TIMEOUT);
        session.setProjectId(userProjectType);
        session.setCreateTimestamp(System.currentTimeMillis());
        session.setUpdateTimestamp(System.currentTimeMillis());
        session.setSessionid(sessionId);
        String user_id = userProjectType + "_" + userid;
        session.setUserid(user_id);
        System.out.println(Requests.getRequestAddr());
        session.setIp(Requests.getRequestAddr());
        session.setObject(Jackson.writeJson(object));
        List<YwSession> ys = ywSessionRepository.findByUserid(user_id);
        if (ys.size() > 0) {
            jdbcTemplate.execute("delete from yw_session where userid='" + user_id + "'");
        }
        session = ywSessionRepository.saveAndFlush(session);
        return sessionId;
    }

    /**
     * 获取当前用户
     *
     * @param sessionid
     * @param userProjectType
     * @return
     */
    public Object getUserObj(String sessionid, String userProjectType) {
        log.info("获取当前用户sessionid:{},userProjectType:{}", sessionid, userProjectType);
        YwSession currentSession = ywSessionRepository.findBySessionidAndProjectId(sessionid, userProjectType);
        ParamPreconditions.checkNotNull(currentSession, CodeEnum.SESSION_INVLID.getCode(),
                CodeEnum.SESSION_INVLID.getMsg());
        long start = System.currentTimeMillis();
        long end = currentSession.getUpdateTimestamp() + currentSession.getPeriod();
        ParamPreconditions.checkArgument(end > start, CodeEnum.SESSION_EXPIRED.getCode(),
                CodeEnum.SESSION_EXPIRED.getMsg());
        ywSessionRepository.updateByUpdateTimestamp(start, sessionid, userProjectType);
        if (Sysconst.USER_PAGODA_AGENT.equals(userProjectType))
            return Jackson.readJson(currentSession.getObject(), PaAgent.class);
        if (Sysconst.USER_PAGODA_MEMBER.equals(userProjectType))
            return Jackson.readJson(currentSession.getObject(), PaMember.class);
        throw new HandlerException(CodeEnum.SESSION_USER_TYPE_ERR.getCode(),
                CodeEnum.SESSION_USER_TYPE_ERR.getMsg(), CodeEnum.SESSION_USER_TYPE_ERR.getMsg());
    }
}
